﻿using System.Linq;
using System.Threading;
using Common.Logging;
using OutDbContext;
using Rmq.Center;
using User.Api.BizExtensions;
using User.Api.Helpers;

namespace Out.TaskRunner.RmqWorkers
{
    public class OrderPayReverseWorker : IWorker
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(OrderPayReverseWorker));

        public void Start(CancellationToken ct)
        {
            if (ct.IsCancellationRequested)
            {
                return;
            }

            using (var consumer = new OrderPayReverseConsumer())
            {
                consumer.Subscribe((id, count, dt, msg, channel) =>
                {
                    if (msg.OrderType == OrderType.刷卡支付订单)
                    {
                        //处理门诊缴费订单支付超时
                        return ProcessMicroPayOrder(msg.OrderId, channel);
                    }

                    return new ConsumedResult { Ack = true };
                });

                while (true)
                {
                    if (ct.IsCancellationRequested)
                    {
                        break;
                    }

                    Thread.Sleep(50);
                }
            }
        }



        /// <summary>
        /// 撤销-支付失败时执行
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="channel"></param>
        /// <returns></returns>
        private ConsumedResult ProcessMicroPayOrder(int orderId, WrapperChannel channel)
        {
            Logger.InfoFormat("shaoma-cx：{0}", orderId);
            using (var ctx = new HzfyWeiXinEntities())
            {
                var order = ctx.MicroPayOrder.IsStatus(MicroPayOrderExtensions.OrderStatus.支付失败).FirstOrDefault(x => x.Id == orderId);
                if (order != null)
                {
                    var res = WeixinPayV3Helper.Reverse("MP" + order.OrderNo, order.WxTransactionId);
                    if (res.ResultCode == "0")
                    {
                        order.PayState = MicroPayOrderExtensions.PayState.已撤销.ToInt32().ToString();
                        order.OrderStatus = MicroPayOrderExtensions.OrderStatus.撤销成功.ToInt32().ToString();
                        order.MicroPayRemark = res.ResultMsg ?? "";
                        ctx.SaveChanges();
                    }
                    else if (res.ResultCode == "1")
                    {
                        order.MicroPayRemark = (order.MicroPayRemark ?? "") + "||" + (res.ResultMsg ?? "");
                        ctx.SaveChanges();
                    }
                    else
                    {
                        //10秒重试
                        return new ConsumedResult
                        {
                            Ack = true,
                            Delay = 10 * 1000
                        };
                    }
                }
            }

            return new ConsumedResult
            {
                Ack = true
            };
        }

    }
}